<?php

namespace App\Http\Controllers\Wechat;

use App\Blocks\Wechat;
use App\Libs\Jidi;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use Illuminate\Http\Request;

class ServerController {
    public function server(){
        $app = Factory::officialAccount(\Config::get('wechat'));
        $app->server->push(function ($message) {
            \Log::debug($message);
            switch ($message['MsgType']) {
                case 'event':
                    switch ($message['Event']){
                        case 'unsubscribe':
                            break;
                        case 'subscribe':
                            global $wechatName;
                            $wechatText =<<<EOF
欢迎来到【{$wechatName}】！

恭喜你！从今以后，你在淘宝买东西可以省下大把的银子了~~

我们这里的天猫淘宝优惠券商品每天一共有8万款！8万款啊！！

用券后的价格真的爽爆！！

不过注意了，这些优惠券都是限时限量的~很火的券可能在半个小时内就会被抢完！

OK，话不多说，赶紧进入底部菜单【领优惠券】，看看有你最近想买的东西么~

记住哦：下单之前，先来搜券！

---------------

更省事的找券方式：

在公众号里发送“找***”，然后点击我发给您的链接，就是您要找的***的优惠券啦~

(如发送：找面膜、找高跟鞋)
EOF;
                            return $wechatText;
                            break;
                    }
                    break;
                case 'text':
                    if(preg_match('/.*找(.*)/i' , $message['Content'] , $match)){
                        if(empty($match[1])){
                            return "您要找什么?";
                        }else{
                            $jidi = new Jidi();
                            $accessToken = $jidi->getToken();
                            $products = curlGet($jidi->getProductsUrl() . "?token={$accessToken}&k={$match[1]}&per=1&page=1&sort=3");
                            $products = json_decode($products);
                            if(isset($products->proList) && !empty($products->proList->data)) {
                                $product = $products->proList->data[0];
                                $data = [
                                    'title' => "您要得{$match[1]}找到了",
                                    'description' => '赶快点我查看更多吧!',
                                    'image' => $product->pic,
                                    'url' => env('WEB_URL')."/index?searchKey={$match[1]}",
                                ];
                                $newsItem = new NewsItem($data);
                                $message = new News([$newsItem]);
                                return $message;
                            }

                            $url = \Config::get('app.url');
                            return "您要找的$match[1]没有找到，建议再重新更换搜索的内容；比如'找面膜'等！也可以去{$url}/index找找，可能由您喜欢的";
                        }
                    }else if(preg_match('/.*优惠券.*/i' , $message->Content , $match)){
                        return "亲，点击进入公众号底部菜单“领优惠券”，您就能搜索任何你想买的东西啦，都有优惠券的哦~";
                    }else{
                        return "亲，很抱歉，我没明白您的意思。24小时内会有人工客服来回答您的问题。如果想找优惠券，请点击进入公众号底部菜单“领优惠券”，就能搜索任何您想买的东西啦，都是有优惠券的哦~";
                    }
                    break;
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        return $app->server->serve();
    }

    /**
     * 设置菜单
     */
    public function setMenu(Request $request){
        $appId = $request->get('appid');

        $wechatBlock = new Wechat();

        $menuData = $wechatBlock->getWechatMenuByAppId($appId);

        $menu = json_decode($menuData->menu, true);

        $app = Factory::officialAccount(\Config::get('wechat'));
        $app->menu->create($menu);
    }

    /**
     * 发送客服消息
     */
    public function sendStaff($openId , $type  , $content){
        $message = '';

        if($type == 'text'){
            $message = new Text(['content' => $content]);
        } elseif($type == 'img'){
            $message = new Image(['media_id' => $content]);
        } elseif($type == 'news'){
            $newsItem = new NewsItem($content);
            $message = new News([$newsItem]);
        }

        if(!empty($message)) {
            $app = Factory::officialAccount(\Config::get('wechat'));
            $staff = $app->customer_service; // 客服管理
            return $staff->message($message)->to($openId)->send();
        }else{
            return false;
        }
    }

    //获取微信js sdk
    /**
     *   [
     *      mehod : 'post',
     *      request_params : [
     *          'apis' : str,
     *          'debug' : true/false   //是否开启调试
     *      ]
     *      response : [
     *          'code' => 'xx'  1success  0 error
     *          'msg'  =>  '消息提示'
     *          'data' => xxx     返回数据
     *      ]
     *   ]
     */
    //参数1, api参数  2,是否开启调试 3不知道, 4是否返回json格式
    public function getJsSdk(Request $request)
    {
        $apis = $request->input('apis');
        if($apis){
            $apis_arr = explode(',',$apis);
        }else{
            $apis_arr = ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo'];
        }

        $app = Factory::officialAccount(\Config::get('wechat'));
        $js = $app->jssdk;

        $debug = false;
        if($request->has('debug')){
            $debug = $request->input('debug');
        }

        if($request->has('url')) {
            $js->setUrl($request->get('url'));
        }

        $config = $js->buildConfig($apis_arr, $debug, $beta = false, $json = true);
        if(!empty($config)){
            return response()->json($config);
        }else{
            return response()->json(['error' => '没有数据']);
        }
    }

    public function login(Request $request){
        $config = \Config::get('wechat');
        $config['oauth']['callback'] .= '?'.http_build_query($request->all());
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        return $oauth->redirect();
    }
}